package com.ninth_group.controller;

import com.ninth_group.dto.UserDTO;
import com.ninth_group.exception.user.PSValidException;
import com.ninth_group.exception.user.UserInfoIsNullException;
import com.ninth_group.exception.user.UsernameException;
import com.ninth_group.result.R;
import com.ninth_group.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * 登录
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;

    // 数据存储在hbase表
    @PostMapping("/login")
    public R login(@RequestBody UserDTO userDTO) throws Exception {
        return userService.login(userDTO);
    }

    // 数据存储在hive表
//    @PostMapping("/login")
//    public R login(@RequestBody UserDTO userDTO, HttpServletRequest request) throws Exception {
//        // 测试阶段, 后端手动添加token到Authorization字段中, 后续删除
//        R login = userService.login(userDTO);
//        String token = (String) login.getData();
//        if (token != null && token.startsWith(JWTConstants.TOKEN_PREFIX)) {
//            // 这里一定要添加到session中, 若是添加到request中, 会导致session丢失, 导致无法获取token
//            request.getSession().setAttribute(JWTConstants.JWT_HEADER_INFO, token);
//        }
//        return login;
////        return userService.login(userDTO);
//    }

    /**
     * 处理UserInfoIsNullException异常
     */
    @ExceptionHandler(UserInfoIsNullException.class)
    public R handleUserInfoIsNullException(UserInfoIsNullException e) {
            return R.fail(e.getMessage());
        }

    @ExceptionHandler(UsernameException.class)
    public R handleUsernameException(UsernameException e) {
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(PSValidException.class)
    public R handlePassWordIsValidException(PSValidException e) {
        return R.fail(e.getMessage());
    }

}
